<template>
  <Card>
    <Form ref="formRef" class="w-full h-full" :model="info">
      <div class="flex-1 flex items-center justify-between mb-4 m-4">
        <img class="flex-1 overflow-hidden max-h-96" :src="oldBgImg" />
        <FormItem class="mb-0 flex-1" name="loginImgUrl">
          <Flex>
            <Upload
              class="w-full flex justify-center"
              :custom-request="customRequest"
              @change="onChange"
              :show-upload-list="false"
              accept="image/png, image/jpeg"
              :max-count="1"
            >
              <img v-if="newBgImg" class="max-h-96" :src="newBgImg" />

              <div v-else class="flex flex-col items-center justify-between">
                <FileImageOutlined class="text-6xl mb-2" />
                <span>点击此处上传</span>
              </div>
            </Upload>
          </Flex>
        </FormItem>
      </div>
      <div class="flex">
        <span class="text-2xl font-semibold flex-1 text-center">原背景图</span>
        <div class="flex-1 flex flex-col items-center">
          <span class="text-2xl font-semibold">新背景图-预览效果</span>
          <span class="text-sm"
            >建议尺寸比例：1920*1080，只能上传jpg/png/jpeg文件，且不超过20Mb</span
          >
        </div>
      </div>

      <div class="w-[700px] mx-auto mt-7">
        <FormItem class="" label="系统名称" :rules="rules" name="systemName">
          <Input v-model:value="info.systemName" />
        </FormItem>
        <FormItem>
          <Flex justify="center">
            <Space>
              <!-- <Button @click="onCancel">取消</Button> -->
              <Button type="primary" @click="onConfirm">确定</Button>
            </Space>
          </Flex>
        </FormItem>
      </div>
    </Form>
  </Card>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useCommonStore } from '@/stores/modules';
import { FileImageOutlined } from '@ant-design/icons-vue';
import {
  Button,
  Card,
  Flex,
  Form,
  FormInstance,
  FormItem,
  FormItemProps,
  Input,
  Modal,
  Space,
  Upload,
  UploadProps,
  message,
} from 'ant-design-vue';
import {
  loginPageConfig,
  updateLoginPageConfig,
  uploadImage,
} from '@/api/system';

const commonStore = useCommonStore();
const oldBgImg = ref('');
const newBgImg = ref('');
const info = ref({
  imgName: '',
  loginImgUrl: '',
  systemName: '',
});

const init = async () => {
  const res = await loginPageConfig();
  const { loginImgUrl, imgName, ...other } = res.data as any;
  // 更新commonStore中背景图同步登录页
  commonStore.loginBgUrl = loginImgUrl;
  oldBgImg.value = loginImgUrl;
  info.value = {
    ...other,
  };
};

init();

const formRef = ref<FormInstance>();
const rules: FormItemProps['rules'] = [
  { required: true, message: '请输入', trigger: 'blur' },
];

const onChange: UploadProps['onChange'] = (res) => {
  if (res.file.status === 'done') {
    const { url, filename } = res.file.response as any;
    newBgImg.value = url;
    info.value.loginImgUrl = filename;
    info.value.imgName = res.file.name;
  }
};

const onConfirm = async () => {
  await formRef.value?.validate();
  await updateLoginPageConfig(info.value);
  message.success('操作成功');
  init();
};

const onCancel = () => {};

const customRequest: UploadProps['customRequest'] = ({
  file,
  filename,
  onError,
  onSuccess,
  onProgress,
}) => {
  const formData = new FormData();
  formData.append(filename || 'file', file);
  formData.append('fileName', file.name);
  uploadImage(formData, {
    skipError: true,
    onUploadProgress: onProgress,
  })
    .then((res) => {
      const { fileHttpUrl, filename } = res.data as any;
      onSuccess?.({ url: fileHttpUrl, filename });
    })
    .catch((err) => {
      Modal.error({
        title: '提示',
        content: err.message,
      });
      onError?.(err);
    });
};
</script>
